package com.tl.sun.ui.dialog;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.blankj.utilcode.utils.LogUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.tl.sun.AppContext;
import com.tl.sun.R;
import com.tl.sun.manager.MDAccountMgr;
import com.tl.sun.manager.MDUserMgr;
import com.tl.sun.model.BaseModel;
import com.tl.sun.model.QrEneity;
import com.tl.sun.model.SessionEnetity;
import com.tl.sun.model.UserEnetity;
import com.tl.sun.ui.activity.MainActivity;
import com.tl.sun.utils.ToastUtil;

import java.lang.reflect.Type;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：HQY on 17/11/1 14:17
 * 邮箱：hqy_xz@126.com
 */

public class QRDialogFragment extends DialogFragment {


    protected Timer mHearBeatTimer;
    protected HeartBeatTask mHeartBeatTask;//心跳
    @Bind(R.id.iv_qr_pic)
    ImageView mIvQrPic;

    private int time = 1;
    private QrEneity mQR;

    public static QRDialogFragment newInstance() {
        Bundle args = new Bundle();
        QRDialogFragment fragment = new QRDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.Dialog_Tips);
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_qr, null);
        builder.setView(view);
        builder.setCancelable(true);
        ButterKnife.bind(this, view);
        getQRUrl();
        return builder.create();
    }


    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.CENTER;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(wlp);
    }

    private void sendLogin() {
        mHearBeatTimer = new Timer(true);
        mHeartBeatTask = new HeartBeatTask();
        mHearBeatTimer.schedule(mHeartBeatTask, 1000, 3000);
    }

    /**
     * 获取二维码图片
     */
    private void getQRUrl() {
        OkGo.post(AppContext.getInstance().getBaseUrl() + "wx/get_qr")
                .tag("qr")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        Type qrType = new TypeToken<BaseModel<QrEneity>>() {
                        }.getType();
                        BaseModel<QrEneity> qrBase;
                        try {
                            qrBase = gson.fromJson(s, qrType);
                        } catch (JsonSyntaxException e) {
                            qrBase = gson.fromJson(s, BaseModel.class);
                        }
                        if (qrBase.getRet().equals("0")) {
                            mQR = qrBase.getData();
                            LogUtils.e("图片连接：" + mQR.getImageUrl());
                            Glide.with(getActivity())
                                    .load(mQR.getImageUrl())
//                                    .placeholder(R.drawable.qr_pic)
                                    .into(mIvQrPic);
                            sendLogin();
                        } else {
                            ToastUtil.showToast(qrBase.getMsg());
                        }

                    }
                });
    }

    /**
     * 循环
     */
    protected class HeartBeatTask extends TimerTask {
        @Override
        public void run() {
            time++;
            if (time > 20) {
                OkGo.getInstance().cancelTag("qr");
                dismiss();
            } else {
                sendScanQr();
            }
        }
    }

    private void sendScanQr() {
        OkGo.post(AppContext.getInstance().getBaseUrl() + "wx/scan_qr")
                .params("sence_id", mQR.getSenceId())
                .tag("qr")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModels = gson.fromJson(s, BaseModel.class);
                        if (baseModels.getRet().equals("0")) {
                            Type userType = new TypeToken<BaseModel<SessionEnetity>>() {
                            }.getType();
                            BaseModel<SessionEnetity> baseModel;
                            try {
                                baseModel = gson.fromJson(s, userType);
                            } catch (JsonSyntaxException e) {
                                baseModel = gson.fromJson(s, BaseModel.class);
                            }
                            SessionEnetity sessionInfo = baseModel.getData();
                            MDAccountMgr.getInstance().setSessionId(sessionInfo.getSession());
                            UserEnetity user = sessionInfo.getUserInfo();
                            MDAccountMgr.getInstance().setLoginType("0");
                            MDUserMgr.getInstance().setAwardFlag(user.getAward_flag());
                            MDUserMgr.getInstance().setId(user.getId());
                            MDUserMgr.getInstance().setUsername(user.getUsername());
                            MDUserMgr.getInstance().setNickname(user.getNick_name());
                            MDUserMgr.getInstance().setChange(user.getChange());
                            MDUserMgr.getInstance().setEmail(user.getEmail());
                            MDUserMgr.getInstance().setPhone(user.getPhone());
                            MDUserMgr.getInstance().setMoney(Double.valueOf(user.getMoney()));
                            MDUserMgr.getInstance().setLastTime(user.getLast_time());
                            MDUserMgr.getInstance().setLastTimeType(user.getLast_time_type());
                            MDUserMgr.getInstance().setStatus(user.getStatus());
                            MDUserMgr.getInstance().setToken(user.getToken());
                            MDUserMgr.getInstance().setTime(user.getnVipTime());
                            MDUserMgr.getInstance().setsTime(user.getsVipTime());
                            MDUserMgr.getInstance().setCoupoum(user.getCoupoum());
                            MDUserMgr.getInstance().setOrigin(user.getOrigin());
                            MDUserMgr.getInstance().setLogin(true);//保存到类
                            MDUserMgr.getInstance().setThreeDayExpire(user.getThreeDayExpire());
                            MDAccountMgr.getInstance().setLogin(true);//保存到内存
                            MDAccountMgr.getInstance().setLoginName(user.getShowNmae());
                            MDAccountMgr.getInstance().setRadiusPass(user.getRadiusPass());
                            MDAccountMgr.getInstance().writeToCache(getActivity());
                            Intent login = new Intent(getActivity(), MainActivity.class);
                            startActivity(login);
                            getActivity().finish();
                            dismiss();
                        }

                    }
                });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != mHearBeatTimer) {
            mHearBeatTimer.cancel();
            mHearBeatTimer = null;
        }
        ButterKnife.unbind(this);
    }
}
